<?php
/**
 * bootstrap.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-10 17:35:59
 * @modified   2023-05-10 17:35:59
 */

namespace Plugin\MultiSeller;

use Beike\Seller\Repositories\SellerRepo;
use Beike\Services\StateMachineService;
use Plugin\MultiSeller\Models\Order;
use Plugin\MultiSeller\Services\ShopService;

class Bootstrap
{
    public function boot()
    {
        $this->addEvents();
    }

    private function addEvents()
    {
        add_hook_filter('admin.components.sidebar.menus', function ($data) {
            $data[] = ShopService::getMenus();

            return $data;
        }, 0);

        add_hook_filter('role.permissions.plugin', function ($data) {
            return array_merge($data, ShopService::getPermissionsTable());
        });
        add_hook_blade('product.detail.after', function ($callback, $output, $data) {
            return view('MultiSeller::partial.product_info_seller', $data);
        });
        // for ShopAPI
        add_hook_filter('resource.product.detail', function ($data) {
            return array_merge($data, ['seller' => ShopService::getSellerByProductId($data['id'])]);
        });
        add_hook_blade('product_list.item.name.before', function ($callback, $output, $data) {
            $productIds  = [];
            if (isset($data['products'])) {
                $productIds = is_array($data['products']) ? array_column($data['products'], 'id') : $data['products']->pluck('id')->toArray();
            } elseif (isset($data['relations'])) {
                $productIds = is_array($data['relations']) ? array_column($data['relations'], 'id') : $data['relations']->pluck('id')->toArray();
            }

            return view('MultiSeller::partial.product_list_item_seller', ['seller' => ShopService::getSellerByProductId($data['product']['id'], $productIds)]);
        });
        add_hook_blade('checkout.products', function ($callback, $output, $data) {
            return view('MultiSeller::partial.checkout_products', $data);
        });
        add_hook_blade('checkout.shipping_method', function ($callback, $output, $data) {
            return '';
        });
        add_hook_filter('service.checkout.show_shipping_method', function ($show) {
            return false;
        }, 0);
        // add_hook_filter('service.cart.data', function ($data) {
        //     $data['carts'] =  ShopService::cartListGroupBySeller($data['carts']);
        //     return $data;
        // });
        add_hook_filter('service.checkout.total_service', function ($totalClass) {
            $totalClass = '\\Plugin\\MultiSeller\\Services\\TotalService';

            return $totalClass;
        });
        // 拆单
        add_hook_filter('repository.order.create.after', function ($data) {
            ShopService::createSubOrder($data['order'], $data['data']);
        });
        // 主订单状态已付款时时处理子订单状态和主订单状态改为已拆分
        add_hook_filter('service.state_machine.change_status.after', function ($data) {
            if ($data['status'] == StateMachineService::UNPAID) {
                $seller = SellerRepo::find($data['order']->seller_id);
                if ($seller) {
                    $seller->notifyNewOrderAlert($data['order']);
                }
            }
            ShopService::changeSubOrderStatus($data['order'], $data['status'], $data['comment'], $data['notify']);
        });
        // 修改状态机，增加“已拆分”状态，对于主订单，状态变为已付款时不执行任何function
        add_hook_filter('service.state_machine.machines', function ($data) {
            $data['machines'] = ShopService::getStateMachines($data['order'], $data['machines']);

            return $data;
        });
        add_hook_filter('service.state_machine.all_statuses', function ($data) {
            $data[] = [
                'status' => 'split',
                'name'   => trans('MultiSeller::common.split'),
            ];

            return $data;
        });

        add_hook_blade('admin.product.list.action', function ($callback, $output, $data) {
            return view('MultiSeller::admin.partial.product_list_action', $data)->render();
        }, 2);

        add_hook_blade('admin.product.list.content.footer', function ($callback, $output, $data) {
            return view('MultiSeller::admin.partial.product_list_action_footer', $data)->render();
        }, 2);

        add_hook_blade('header.top.right', function ($callback, $output, $data) {
            return view('MultiSeller::shop.header_top_right', $data)->render();
        });

        add_hook_filter('admin.order.index.data', function ($data) {
            $data['orders']->map(function ($order) {
                $sellerName    = SellerRepo::find($order->seller_id)->store_name ?? trans('MultiSeller::common.self');
                $order->number = $order->number . " - [$sellerName]";

                return $order;
            });

            return $data;
        });

        add_hook_filter('menu.content', function ($data) {
            $sid = request()->sid;
            if (! $sid) {
                return $data;
            }
            $data = ShopService::getSellerMenus($sid);

            return $data;
        }, 0);

        add_hook_filter('cart.index.data', function ($data) {
            if (isset($data['data'])) { // beikeshop1.5.1及之前的版本多了data一层，1.5.2以后没有data一层。
                $data['data']['carts'] = ShopService::cartListGroupBySeller($data['data']['carts']);
            } else {
                $data['carts'] = ShopService::cartListGroupBySeller($data['carts']);
            }

            return $data;
        }, 0);

        add_hook_filter('cart.select.data', function ($data) {
            $data['carts'] = ShopService::cartListGroupBySeller($data['carts']);

            return $data;
        }, 0);

        add_hook_filter('cart.update.data', function ($data) {
            $data['carts'] = ShopService::cartListGroupBySeller($data['carts']);

            return $data;
        }, 0);

        add_hook_filter('cart.destroy.data', function ($data) {
            $data['carts'] = ShopService::cartListGroupBySeller($data['carts']);

            return $data;
        }, 0);

        add_hook_filter('checkout.index.data', function ($data) {
            $data['carts']['multi_carts'] =  ShopService::cartListGroupBySeller($data['carts']['carts']);

            return $data;
        }, 0);

        add_hook_filter('checkout.update.data', function ($data) {
            $data['carts']['multi_carts'] =  ShopService::cartListGroupBySeller($data['carts']['carts']);

            return $data;
        }, 0);
    }
}
